package com.aiyige.page.my.merchandisemanagement.mmtraingcard;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.db.dao.TraingCardDBModelDao;
import com.aiyige.base.db.table.TraingCardDBModel;
import com.aiyige.base.eventbus.EventCopyTraingCardFinish;
import com.aiyige.base.eventbus.EventMMPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventMMTraingCardFilter;
import com.aiyige.base.eventbus.EventMMUploadUpdate;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.merchandisemanagement.MMFilterable;
import com.aiyige.page.my.merchandisemanagement.mmtraingcard.adapter.MMTraingCardAdapter;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.LocalServerCommonDataView;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MMTraingCardPage#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MMTraingCardPage extends BaseFragment implements MMFilterable, CommonDataView.RetrofitStub, LocalServerCommonDataView.OperationStub {
    @BindView(R.id.cdv)
    LocalServerCommonDataView cdv;
    Unbinder unbinder;
    MMTraingCardAdapter mmTraingCardAdapter;

    Dao<TraingCardDBModel, String> dao;
    Integer filter = null;
    public static final int MOMENT_FILTER_ALL = 0;
    public static final int MOMENT_FILTER_PUBLISHED = 1;
    public static final int MOMENT_FILTER_NOT_PUBLISHED = 2;
    public static final int MOMENT_FILTER_IN_REVIEW = 3;
    public static final int MOMENT_FILTER_REJECTED = 4;

    public MMTraingCardPage() {
    }


    public static MMTraingCardPage newInstance() {
        MMTraingCardPage fragment = new MMTraingCardPage();
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMMTraingCardFilter event) {
        cdv.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMMUploadUpdate event) {
        mmTraingCardAdapter.getEventBus().post(new EventPublishProgressStatusUpdate());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMMPublishProgressStatusUpdate event) {
        mmTraingCardAdapter.getEventBus().post(new EventPublishProgressStatusUpdate());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_mmtraing_card, container, false);
        unbinder = ButterKnife.bind(this, view);
        dao = TraingCardDBModelDao.getDao();
        mmTraingCardAdapter = new MMTraingCardAdapter(getActivity());
        cdv.config(mmTraingCardAdapter, this, this);


        mmTraingCardAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TraingCardDBModel traingCardDBModel = mmTraingCardAdapter.getItem(position);
                switch (traingCardDBModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                    case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                    case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                    case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                    case PublishUtil.PROGRESS_STATUS_UPLOADING:
                    case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                    case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                        break;
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                        ToastX.show(R.string.server_transcoding);
                        break;
                    default:
                        Router.start(traingCardDBModel.getRouter());
                        break;
                }

            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        cdv.getRecyclerView().setAdapter(null);
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        Integer momentFilter = MOMENT_FILTER_ALL;
        if (filter != null) {
            switch (filter) {
                case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    momentFilter = MOMENT_FILTER_PUBLISHED;
                    break;
                case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    momentFilter = MOMENT_FILTER_NOT_PUBLISHED;
                    break;
                case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    momentFilter = MOMENT_FILTER_IN_REVIEW;
                    break;
                case PublishUtil.PROGRESS_STATUS_REJECT:
                    momentFilter = MOMENT_FILTER_REJECTED;
                    break;
            }
        }
        return ApiManager.getService().merchandiseManagementMoment(100, currentPage, Arrays.asList(Moment.SUBJECT_TRAINING_CARD), momentFilter, 1);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                resultList.add(TraingCardDBModel.parse(record));
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    @Override
    public List query() {
        if (filter != null && filter != PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
            return new LinkedList();
        try {
            DeleteBuilder<TraingCardDBModel, String> deleteBuilder = dao.deleteBuilder();
            deleteBuilder.where()
                    .eq(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT);
            deleteBuilder.delete();
            return dao.queryBuilder()
                    .where()
                    .eq(TraingCardDBModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                    .and()
                    .ne(TraingCardDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                    .and()
                    .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .and()
                    .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .and()
                    .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .and()
                    .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                    .and()
                    .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .query();
        } catch (Exception e) {
            return new LinkedList();
        }
    }

    @Override
    public int compare(Object o1, Object o2) {
        long diff = ((TraingCardDBModel) o2).getReleaseDate() - ((TraingCardDBModel) o1).getReleaseDate();
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public boolean equal(Object o1, Object o2) {
        TraingCardDBModel model1 = (TraingCardDBModel) o1;
        TraingCardDBModel model2 = (TraingCardDBModel) o2;
        return model1.getId().equals(model2.getId()) || model1.getGoodsId().equals(model2.getGoodsId());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventCopyTraingCardFinish event) {
        if (event.getResultCode() == EventCopyTraingCardFinish.RESULT_OK) {
            cdv.refresh();
        }
    }

    @Override
    public void setFilter(Integer filter) {
        this.filter = filter;
        EventBus.getDefault().post(EventMMTraingCardFilter.newBuilder().build());
    }
}
